<template>
  <div>
    <Row style="margin-bottom:5px;">
      <Input search clearable v-model="searchKey" placeholder="输入表名称或描述信息进行过滤" @on-search="SearchTables" @on-enter="SearchTables" @on-clear="SearchTables" />
    </Row>
    <div :style="tableListStyle" style="overflow-x:hidden;overflow-y:auto;">
      <div v-for="(item, index) in tables" @click="SelectedTable(item)" class="bg-success" :class="activeTable == item ? 'bg-warning' : 'bg-success'">
        <h5>
          {{ item.table_name }}
          <i>({{ item.table_rows || '0' }})</i>
          <Avatar style="background-color: #87d068">{{ index + 1 }}</Avatar>
        </h5>
        <i v-if="item.table_comment">{{ item.table_comment }}</i>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dbIndex: {
      type: [String, Number],
      default: 0
    },
    schema: String,
    tableListStyle: [String, Object]
  },
  data() {
    return {
      searchKey: '',
      tables: [],
      tempDatas: [],
      activeTable: {}
    };
  },
  watch: {
    activeTable(value) {
      (value || {}).totalTables = this.tables.length;

      this.$emit('change', value);
    },
    schema(value) {
      this.schema = value;
      this.searchKey = '';

      this.$nextTick(() => {
        this.GetTables();
      });
    }
  },
  methods: {
    SearchTables() {
      if (this.tempDatas) {
        let key = (this.searchKey || '').toUpperCase();

        if (key.trim()) {
          this.tables = this.tempDatas.filter(i => (i.table_name || '').toUpperCase().includes(key) || (i.table_comment || '').toUpperCase().includes(key));
        } else {
          this.tables = this.tempDatas;
        }

        this.activeTable = this.tables[0];
        this.activeTable.totalTables = this.tables.length;

        this.$emit('change', this.activeTable);
      }
    },
    ResetSearch() {
      this.searchKey = '';
      this.SearchTables();
    },
    SelectedTable(table) {
      this.activeTable = table;
    },
    GetTables() {
      this.$http.get(`/api/${this.$route.query.dbtype}/${this.dbIndex}/${this.schema}/tables`).then(res => {
        this.tables = this.tempDatas = res.datas;
        this.activeTable = this.tables[0];

        this.$emit('tablesLoaded', res.datas.length);
      });
    }
  }
};
</script>

<style lang="less" scoped>
h5 {
  font-size: 13px;
  font-weight: bold;
  position: relative;
  padding-bottom: 2px;
  > i {
    font-size: 10px;
    font-weight: normal;
    margin-left: 10px;
  }

  > .ivu-avatar {
    position: absolute;
    top: -6px;
    right: -13px;
  }
}

.bg-info,
.bg-success {
  margin-bottom: 5px;
  cursor: pointer;
  padding: 8px 15px;
  width: calc(100% - 5px);

  > i {
    width: 100%;
    display: inline-block;
    font-size: 10px;
    font-weight: normal;
    font-style: italic;
  }
}
</style>
